/**
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * 
 */
package org.jiopi.ibean.share;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import sun.misc.CompoundEnumeration;

/**
 * 
 * 本地Jar优先的ClassLoader
 * 与URLClassLoader的不同点是优先使用给定url范围的jar进行加载
 * 如果加载不到,才使用parent的(如果存在的话)
 * 
 * 
 * 
 * @since 2010.4.15
 *
 */
public class LocalJarPriorClassLoader extends URLClassLoader {
	
	private final ClassLoader parentClassLoader; 

	public LocalJarPriorClassLoader(URL[] urls) {
		super(urls,null);
		parentClassLoader = null;
	}
	
	public LocalJarPriorClassLoader(URL[] urls,ClassLoader parent ) {
		super(urls,null);
		parentClassLoader = parent;
	}
	
	public Class<?> loadClass( String name ) throws ClassNotFoundException {
		if("org.dom4j.DocumentFactory".equals(name) )System.out.println("load >> by LocalJarPriorClassLoader >> "+name);
			Class<?> c = null;
			try {
				//优先调用本地Jar
				c = super.loadClass( name );
			} catch ( ClassNotFoundException e ) {
				if(parentClassLoader!=null) c = parentClassLoader.loadClass(name);
				else throw e;
			}
			return c;
	}
	
	public URL getResource( String name ) {
		URL url = super.getResource(name);
		if(url == null && parentClassLoader!=null){
			url = parentClassLoader.getResource(name);
		}
		return url;
	}
	
	
	@SuppressWarnings("unchecked")
	public Enumeration<URL> getResources( String name ) throws IOException {
		if(parentClassLoader == null) return super.getResources( name );
		else{
			Enumeration[] tmp = new Enumeration[2];
			tmp[0] = parentClassLoader.getResources(name);
			tmp[1] = super.getResources( name );
			return new CompoundEnumeration(tmp);
		}
		
	}

}
